package top.shiyiri.connections;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author Aunean
 * @date 2022/1/20 12:21
 * @Description DBCP数据库连接池使用
 */
public class DBCPTest {

    //方式一
    @Test
    public void test1() throws SQLException {
        //创建了DBCP数据库连接池
        BasicDataSource source = new BasicDataSource();

        //设置基本信息
        source.setDriverClassName("com.mysql.cj.jdbc.Driver");
        source.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8");
        source.setUsername("root");
        source.setPassword("123456");

        //设置其他涉及数据库连接池的属性
        source.setInitialSize(10);
        source.setMaxActive(10);

        Connection conn = source.getConnection();
        System.out.println(conn);
    }

    //方式二：使用配置文件
    @Test
    public void test2() throws Exception {

        Properties pros = new Properties();
        //方式一
        InputStream is = ClassLoader.getSystemResourceAsStream("dbcp.properties");
        //方式二
        //FileInputStream is = new FileInputStream("src/dbcp.properties");

        pros.load(is);
        //创建一个DBCP数据库连接池
        DataSource source = BasicDataSourceFactory.createDataSource(pros);

        Connection conn = source.getConnection();
        System.out.println(conn);
    }
}
